#include "scannercontrol.h"
#include <QMutexLocker>

// 初始化静态成员变量
ScannerControl* ScannerControl::m_instance = nullptr;
QMutex ScannerControl::m_mutex;

ScannerControl::ScannerControl(QObject *parent)
    : QObject{parent}
{
    m_Scanner = new QSerialPort(this);
    // 连接串口数据接收信号与处理槽函数
    QObject::connect(m_Scanner,&QSerialPort::readyRead,this,&ScannerControl::read_Scanner_Result_Slots);    
}

ScannerControl::~ScannerControl()
{
    // 关闭串口并释放资源
    if (m_Scanner->isOpen()) {
        m_Scanner->close();
    }
    m_Scanner->deleteLater();
}

ScannerControl *ScannerControl::getInstance(QObject *parent)
{
    // 双重检查锁定实现线程安全的单例
    if (!m_instance) {
        QMutexLocker locker(&m_mutex); // 自动加锁/解锁
        if (!m_instance) {
            m_instance = new ScannerControl(parent);
        }
    }
    return m_instance;
}

void ScannerControl::setScannerConnectParameter(QString serialPort,
                                                QString baudRate,
                                                QString dataBit,
                                                QString parityBit,
                                                QString stopBit)
{
    QSerialPort::BaudRate set_BaudRate;
    QSerialPort::DataBits set_DataBit;
    QSerialPort::Parity   set_ParityBit;
    QSerialPort::StopBits set_StopBit;

    // 设置波特率
    if("115200" == baudRate)        set_BaudRate = QSerialPort::Baud115200;
    else if("57600" == baudRate)    set_BaudRate = QSerialPort::Baud57600;
    else if("38400" == baudRate)    set_BaudRate = QSerialPort::Baud38400;
    else if("19200" == baudRate)    set_BaudRate = QSerialPort::Baud19200;
    else if("9600" == baudRate)     set_BaudRate = QSerialPort::Baud9600;
    else if("4800" == baudRate)     set_BaudRate = QSerialPort::Baud4800;
    else if("2400" == baudRate)     set_BaudRate = QSerialPort::Baud2400;
    else                            set_BaudRate = QSerialPort::Baud1200;

    // 设置数据位
    if("8" == dataBit)              set_DataBit = QSerialPort::Data8;
    else if("7" == dataBit)         set_DataBit = QSerialPort::Data7;
    else if("6" == dataBit)         set_DataBit = QSerialPort::Data6;
    else                            set_DataBit = QSerialPort::Data5;

    // 设置校验位
    if("None" == parityBit)         set_ParityBit = QSerialPort::NoParity;
    else if("Even" == parityBit)    set_ParityBit = QSerialPort::EvenParity;
    else if("Odd" == parityBit)     set_ParityBit = QSerialPort::OddParity;
    else if("Mark" == parityBit)    set_ParityBit = QSerialPort::MarkParity;
    else                            set_ParityBit = QSerialPort::SpaceParity;

    // 设置停止位
    if("1" == stopBit)              set_StopBit = QSerialPort::OneStop;
    else if("1.5" == stopBit)       set_StopBit = QSerialPort::OneAndHalfStop;
    else                            set_StopBit = QSerialPort::TwoStop;

    // 应用串口设置
    m_Scanner->setPortName(serialPort);
    m_Scanner->setBaudRate(set_BaudRate);
    m_Scanner->setDataBits(set_DataBit);
    m_Scanner->setParity(set_ParityBit);
    m_Scanner->setStopBits(set_StopBit);
    // 设置流控制为无（默认值，显式设置更清晰）
    m_Scanner->setFlowControl(QSerialPort::NoFlowControl);
}

void ScannerControl::connectToDevice()
{
    if (m_Scanner->isOpen()) {
        m_Scanner->close(); // 先关闭已打开的连接
    }

    if(m_Scanner->open(QIODevice::ReadWrite)) {
        qDebug() << "Cpp: 扫码枪 连接成功，端口：" << m_Scanner->portName();
    } else {
        qDebug() << "Cpp: 扫码枪 连接失败，错误：" << m_Scanner->errorString();
    }
}

void ScannerControl::read_Scanner_Result_Slots()
{
    qDebug()<<"当前扫码枪线程 : "<<QThread::currentThreadId();

    if (m_Scanner->bytesAvailable() <= 0) return;

    QByteArray readResult = m_Scanner->readAll();
    if (!readResult.isEmpty())
    {

        // qDebug()<<"扫码枪读取出:"<<readResult;
        switch(Current_QR_Type())
        {
        case 1:{
            qDebug()<<"扫码触发 - 长风离线";
            emit send_Scanner_Result_OutLine_Signal(readResult);
            break;
        }
        case 2:{
            qDebug()<<"扫码触发 - 速制离线";
            emit send_Scanner_Result_OutLine_Signal(readResult);
            break;
        }
        case 3:{
            qDebug()<<"扫码触发 - 画门窗";
            emit send_Scanner_Result_OutLine_Signal(readResult);
            break;
        }
        case 4:{
            qDebug()<<"扫码触发 - 创品离线";
            emit send_Scanner_Result_OutLine_Signal(readResult);
            break;
        }
        case 5:{
            qDebug()<<"扫码触发 - 新格尔离线";
            emit send_Scanner_Result_OutLine_Signal(readResult);
            break;
        }
        case 6:{
            qDebug()<<"扫码触发 - 长风在线";
            emit send_Scanner_Result_ChangFeng_Signal(readResult);
            break;
        }
        case 7:{
            qDebug()<<"扫码触发 - 新格尔在线";
            emit send_Scanner_Result_XinGeEr_Signal(readResult);
            break;
        }
        case 8:{
            qDebug()<<"扫码触发 - 速制在线";
            emit send_Scanner_Result_SuZhi_Signal(readResult);
            break;
        }
        case 9:{
            qDebug()<<"扫码触发 - 创品在线";
            emit send_Scanner_Result_ChuangPin_Signal(readResult);
            break;
        }
        default:{
            qDebug()<<"扫码触发其他";
            break;
        }

        }
    }
}



int ScannerControl::Current_QR_Type() const
{
    return m_Current_QR_Type;
}

void ScannerControl::setCurrent_QR_Type(int newCurrent_QR_Type)
{
    if (m_Current_QR_Type == newCurrent_QR_Type)
        return;
    m_Current_QR_Type = newCurrent_QR_Type;
    emit Current_QR_TypeChanged();
}
